package com.itheima.reggie.common;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
@Slf4j
//字定义元数据对象处理器 作用:统一为公共字段赋值
public class MyMetaObjecthandler implements MetaObjectHandler {
    @Override//插入操作,自动填充
    public void insertFill(MetaObject metaObject) {
        log.info("插入操作,自动填充...");
        Long userId = BaseContext.getThreadId();
        metaObject.setValue("createTime", LocalDateTime.now());//创建时间自动填充
        metaObject.setValue("updateTime",LocalDateTime.now());
        metaObject.setValue("createUser",userId);
        metaObject.setValue("updateUser",userId);
    }
    //修改操作,自动填充
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("修改操作,自动填充...");
        //从ThreadLocal工具类中获取当前用户id
        Long userId = BaseContext.getThreadId();
        metaObject.setValue("updateTime",LocalDateTime.now());
        metaObject.setValue("updateUser",userId);
//        long threadId = Thread.currentThread().getId();
//        log.info("updateFill线程id:"+threadId);
    }
}
